﻿using System;
using System.Xml;
using System.Windows.Forms;
using SdmxMl.Common;
using SdmxMl.Manager;

namespace SdmxMl.Panels
{
    /// <summary>
    /// Control for annotation detail edition
    /// </summary>
    public partial class PanelAnnotationList : PanelBase
    {
        #region Internal members

        IAnnotationList annlist;
        private bool _isFinal;
        private Button butCut;
        private Button butCopy;
        private Button butPaste;

        #endregion

        #region Properties

        public Button ButtonCut
        {
            get { return butCut; }
            set
            {
                butCut = value;
                if (butCut != null)
                    butCut.Click +=new EventHandler(butCut_Click);
            }
        }

        public Button ButtonCopy
        {
            get { return butCopy; }
            set
            {
                butCopy = value;
                if (butCopy != null)
                    butCopy.Click += new EventHandler(butCopy_Click);
            }
        }

        public Button ButtonPaste
        {
            get { return butPaste; }
            set
            {
                butPaste = value;
                if (butPaste != null)
                    butPaste.Click += new EventHandler(butPaste_Click);
            }
        }

        #endregion

        #region C'tor

        public PanelAnnotationList()
        {
            InitializeComponent();
            EnableGrigButtons(false);
         //   dataGridViewAnnot.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders;
            SetGridTextWidth();
        }

        private void SetGridTextWidth()
        {
            dataGridViewAnnot.Columns[3].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            dataGridViewAnnot.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }
        #endregion

        #region Buttons activation

        /// <summary>Update Grid buttons state</summary>
        /// <param name="enable">If true buttons are enabled</param>
        protected void EnableGrigButtons(bool enable)
        {
            butAdd.Enabled = enable && _isFinal == false;
            butEdit.Enabled = enable && dataGridViewAnnot.RowCount > 0;
            butRemove.Enabled = enable && _isFinal == false && dataGridViewAnnot.SelectedCells.Count > 0;
            buttonNavigateUrn.Visible = annlist != null && annlist.AnnotationList != null &&
            annlist.AnnotationList.HasUrn;
            buttonAddUrl.Enabled = enable && _isFinal == false;

            if (butCut != null)
                butCut.Enabled = enable && _isFinal == false && dataGridViewAnnot.SelectedCells.Count > 0;
            if (butCopy != null)
                butCopy.Enabled = dataGridViewAnnot.SelectedCells.Count > 0;
            if (butPaste != null)
                butPaste.Enabled = enable && _isFinal == false && CopyPasteManager.AnnotationInfo != null;
        }

        private void ButVisible(bool visible)
        {
            butAdd.Visible = visible;
            butEdit.Visible = visible;
            butRemove.Visible = visible;
            buttonNavigateUrn.Visible = visible;
            buttonAddUrl.Visible = visible;
        }

        #endregion

        #region Binding

        public void BindFromNode(object ob, bool isFinal)
        {
            _isFinal = isFinal;
            annlist = null;
            annlist = ob as IAnnotationList;
            UpdateDataGrid(annlist);
        }

        private void UpdateDataGrid(IAnnotationList annlist)
        {
            if (annlist != null)
            {
                dataGridViewAnnot.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders;
                dataGridViewAnnot.DataSource = annlist.AnnotationList.AsDataTable();
                SetGridTextWidth();
                EnableGrigButtons(true);

            }
            else
            {
                AnnotationList al = new AnnotationList();
                dataGridViewAnnot.DataSource = al.AsDataTable();
                EnableGrigButtons(false);
            }

        }
        #endregion

        #region Buttons Events

        private void butEdit_Click(object sender, EventArgs e)
        {
            DlgEditAnnotation aDlg = new DlgEditAnnotation();
            int rowIndex = 0;
            if (dataGridViewAnnot.SelectedCells.Count > 0)
                rowIndex = dataGridViewAnnot.SelectedCells[0].RowIndex;

            if (rowIndex < annlist.AnnotationList.Count)
            {
                aDlg.Ann = annlist.AnnotationList[rowIndex];
                aDlg.IsFinal = _isFinal;
                aDlg.ShowDialog(this);
                UpdateDataGrid(annlist);
            }
        }

        private void AddAnnotation(Annotation a)
        {
            annlist.AnnotationList.Add(a);
            UpdateDataGrid(annlist);
            dataGridViewAnnot.Rows[dataGridViewAnnot.Rows.Count - 1].Selected = true;
        }

        private void butAdd_Click(object sender, EventArgs e)
        {
            AddAnnotation( new Annotation("UNDEFINED"));
        }

        private void butRemove_Click(object sender, EventArgs e)
        {
            int rowIndex = 0;
            if (dataGridViewAnnot.SelectedCells.Count > 0)
            {
                rowIndex = dataGridViewAnnot.SelectedCells[0].RowIndex;
                if (rowIndex < annlist.AnnotationList.Count)
                {
                    annlist.AnnotationList.RemoveAt(rowIndex);
                    UpdateDataGrid(annlist);
                }
            }
        }

        private void buttonNavigateUrn_Click(object sender, EventArgs e)
        {
            if (annlist != null && annlist.AnnotationList != null)
            {
                // If current one is URN, use it else use 1st one
                int rowIndex = 0;
                if (dataGridViewAnnot.SelectedCells.Count > 0)
                {
                    rowIndex = dataGridViewAnnot.SelectedCells[0].RowIndex;
                    if (rowIndex < annlist.AnnotationList.Count)
                    {
                        Annotation a = null;
                        if (annlist.AnnotationList[rowIndex].Url != null)
                            a = annlist.AnnotationList[rowIndex];
                        else
                        {
                            foreach (Annotation au in annlist.AnnotationList)
                                if (au.Url != null)
                                {
                                    a = au;
                                    break;
                                }
                        }
                        if (a != null)
                        {
                            try
                            {
                                using (new SdmxMl.Helper.CWaitCursor())
                                {
                                    // If URN try to get it if not already in memory
                                    ArtefactRefTyped art = UrnManager.UrnToArtefactRefTyped(a.Url.ToString());
                                    if (art != null)
                                    {
                                        UrnParser p = new UrnParser(a.Url.ToString());

                                        // If already in memory, navigate otherwhile get from regidtry
                                        if (NavigationManager.LocatenavigateProject(art.Type, art.FullIdent, p) == null)
                                            NavigationManager.NavigateWithRegistry(art.Type, art.FullIdent, true, p);

                                    }
                                    else if (a.Type == "FSO_PORTAL")
                                    {


                                        System.Net.WebClient webclient = new System.Net.WebClient();
                                        // webclient.Credentials = new NetworkCredential("UA....
                                        XmlDocument xDoc = new XmlDocument();
                                        xDoc.Load(webclient.OpenRead(a.Url));

                                        ReferenceManager.TreeMgr.LoadSdmxArtefact(null, true, xDoc);
                                    }
                                    else
                                    {
                                        // Try to process document
                                        System.Diagnostics.Process myProc;
                                        myProc = System.Diagnostics.Process.Start(a.Url.ToString());
                                    }
                                }
                            }

                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "Error");
                            }
                        }
                    }
                }
            }
        }

        private void buttonAddUrl_Click(object sender, EventArgs e)
        {
            ArtefactRefTyped art = ReferenceManager.ArTypedCopyInstance as ArtefactRefTyped;
            if (art != null)
            {
                if (annlist != null && annlist.AnnotationList != null)
                {
                    Annotation ann = new Annotation("ARTEFACT_URN");
                    ann.Title = art.Type.ToString();
                    ann.Url = new Uri(ReferenceManager.ArTypedCopyInstanceUrn);

                    //ann.Text.UpdateDefaultText(art.FullIdent);
                    annlist.AnnotationList.Add(ann);
                    UpdateDataGrid(annlist);

                }
            }
        }

        void butCopy_Click(object sender, EventArgs e)
        {
            try
            {
                int rowIndex = 0;
                if (dataGridViewAnnot.SelectedCells.Count > 0)
                {
                    rowIndex = dataGridViewAnnot.SelectedCells[0].RowIndex;
                    if (rowIndex < annlist.AnnotationList.Count)
                    {
                        CopyPasteManager.AnnotationInfo = annlist.AnnotationList[rowIndex].Clone();
                        EnableGrigButtons(true);
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }

        void butCut_Click(object sender, EventArgs e)
        {
            try
            {
                int rowIndex = 0;
                if (dataGridViewAnnot.SelectedCells.Count > 0)
                {
                    rowIndex = dataGridViewAnnot.SelectedCells[0].RowIndex;
                    if (rowIndex < annlist.AnnotationList.Count)
                    {
                        CopyPasteManager.AnnotationInfo = annlist.AnnotationList[rowIndex].Clone();
                        butRemove_Click(this, EventArgs.Empty);
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }

        void butPaste_Click(object sender, EventArgs e)
        {
            try
            {
                AddAnnotation(CopyPasteManager.AnnotationInfo.Clone());
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }


        #endregion
    }
            
    
}
